<?php
require APPPATH.'libraries/ApiController.php';
class category extends ApiController {
	public function __construct()
	{
		parent::__construct();
	}
	
	public function list(){
		$token=$this->verifyToken();
		if($token){
			$this->db->where("shopid",$token["shopid"]);
			$this->db->order_by("order",'desc');
			$list=$this->db->get("product_category")->result_array();		
			$this->WRITE("code",1);
			$this->WRITE("list",$list);
			$this->RESPONSE();
		}
	}

	public function create(){
		$token=$this->verifyToken();
		if($token){
			$data=$this->getKeys([
			["title",true,"分类名称"],
			["desc",false,"分类描述",""],
			["order",true,"排序"]],'post');
			
			$data["shopid"]=$token["shopid"];
			$nd=array(
				"title"=>$data["title"],
				"order"=>$data["order"],
				"desc"=>$data["desc"],
				"shopid"=>$data["shopid"]);
				
			$this->db->insert("product_category",$data);
			
			$nd["cateid"]=$this->db->insert_id();
			$this->WRITE("code",1);
			$this->WRITE("data",$nd);
			$this->WRITE("msg","创建分类成功");
			$this->RESPONSE();
		}
	}
	
	public function update(){
		$token=$this->verifyToken();
		if($token){
			$data=$this->getKeys([
			["cateid",true,"类目id"],
			["title",true,"分类名称"],
			["desc",false,"描述",""],
			["order",true,"排序"]],'post');
			
			$data["shopid"]=$token["shopid"];
			
			$this->db->where("cateid",$data["cateid"]);
			$this->db->update("product_category",$data);
			
			$this->db->where("cateid",$data["cateid"]);
			$cdata=$this->db->get("product_category")->row_array();

			$this->WRITE("code",1);
			$this->WRITE("data",$cdata);
			$this->WRITE("msg","更新分类成功");
			$this->RESPONSE();
		}
	}
	
	
	public function remove(){
		$token=$this->verifyToken();
		if($token){
			$data=$this->getKeys([
			["cateid",true,"分类id"]],'post');
			
			//查看当前分类是否有商品
			$this->db->where("cateid",$data["cateid"]);
			$count=$this->db->select("count(*) as count")->get("product")->row_array()["count"];
			if($count>0){
				$this->WRITE("code",0);
				$this->WRITE("msg","此分类下有有商品，请将商品移动到其它分类后再操作!");
				$this->RESPONSE();
				exit();
			}
			$this->db->where("cateid",$data["cateid"]);
			$this->db->delete("product_category");

			$this->WRITE("code",1);
			$this->WRITE("msg","删除成功");
			$this->RESPONSE();
		}
	}
	
	
	
}